<template>
  <div>
    <!--    <el-form ref="queryFormRef" :inline="true" :model="queryParams" class="demo-form-inline" v-hasPermi="['sa:report:query']">-->
    <!--      <el-form-item label="创建人" prop="createBy">-->
    <!--        <el-input v-model.trim="queryParams.createBy" size="small" clearable :minlength="100" placeholder="请输入创建人"></el-input>-->
    <!--      </el-form-item>-->
    <!--      <el-form-item>-->
    <!--        <el-button type="primary" icon="el-icon-search" size="mini" @click="searchHandler">查询</el-button>-->
    <!--        <el-button icon="el-icon-refresh-right" size="mini" @click="resetHandler">重置</el-button>-->
    <!--      </el-form-item>-->
    <!--    </el-form>-->

    <div class="grid-content bg-purple">
      <el-button type="primary" icon="el-icon-refresh" v-hasPermi="['after:workorder:service:query']" size="mini"
                 @click="searchHandler">刷新
      </el-button>
      <el-button
        v-if="(workorder.status === '进行中' && $auth.hasPermi('after:workorder:service:add')) || $auth.hasPermi('after:workorder:edit')"
        plain type="primary" size="mini" icon="el-icon-plus"
        @click="openDialog(null)">增加
      </el-button>
    </div>

    <div v-if="device !== 'mobile'">
      <el-table ref="tableRef" :data="tableData" v-loading="loading" highlight-current-row max-height="500"
                v-horizontal-scroll="'auto'" style="width: 100%;margin-top: 10px;">
        <!--      <el-table-column type="expand" label="展开">-->
        <!--        <template slot-scope="scope">-->
        <!--          <div class=" img-box" v-if="scope.row.deviceImage.length > 2">-->
        <!--            <div class=" img-box justify-content">设备照片</div>-->
        <!--            <div v-for="(url, i) in (scope.row.deviceImage.split(','))" :key="i" style="display: inline-block;">-->
        <!--              <el-image lazy style="width: 160px; height: auto;" fit="contain" :src="env + url"-->
        <!--                @click="handlePictureCardPreview(url)">-->
        <!--                <div slot="error" class="image-slot">-->
        <!--                  <i class="el-icon-picture-outline"></i>-->
        <!--                </div>-->
        <!--              </el-image>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--          <div class=" img-box flex justify-content" v-else>无设备照片</div>-->
        <!--          <div class=" img-box" v-if="scope.row.maintainImage.length > 2">-->
        <!--            <div class=" img-box justify-content">维修照片</div>-->
        <!--            <div v-for="(url, i) in (scope.row.maintainImage.split(','))" :key="i" style="display: inline-block;">-->
        <!--              <el-image lazy style="width: 160px; height: auto;" fit="contain" :src="env + url"-->
        <!--                @click="handlePictureCardPreview(url)">-->
        <!--                <div slot="error" class="image-slot">-->
        <!--                  <i class="el-icon-picture-outline"></i>-->
        <!--                </div>-->
        <!--              </el-image>-->
        <!--            </div>-->
        <!--          </div>-->
        <!--          <div class=" img-box flex justify-content" v-else>无维修照片</div>-->
        <!--        </template>-->
        <!--      </el-table-column>-->
        <el-table-column property="name" label="设备名称" align="center"/>
        <el-table-column property="num" label="数量" align="center"/>
        <el-table-column property="status" label="状态" align="center"/>
        <el-table-column property="nowStatus" label="现状态" align="center"/>
        <el-table-column property="description" label="维修简述" align="center"/>
        <el-table-column property="deviceImage" label="设备图片" align="center" width="100">
          <template slot-scope="scope">
            <div class=" img-box" v-if="scope.row.deviceImage.length > 2">
              <div>
                <el-image
                  style="width: 80px; height: auto;"
                  fit="contain"
                  :src="env + scope.row.deviceImage.split(',')[0]"
                  :preview-src-list="scope.row.deviceImage.split(',').map(i=> (env + i))"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </div>
            <div class=" img-box justify-content" v-else>无</div>
          </template>
        </el-table-column>
        <el-table-column property="maintainImage" label="维修图片" align="center" width="100">
          <template slot-scope="scope">
            <div class=" img-box" v-if="scope.row.maintainImage.length > 2">
              <div>
                <el-image
                  style="width: 80px; height: auto;"
                  fit="contain"
                  :src="env + scope.row.maintainImage.split(',')[0]"
                  :preview-src-list="scope.row.maintainImage.split(',').map(i=> (env + i))"
                >
                  <div slot="error" class="image-slot">
                    <i class="el-icon-picture-outline"></i>
                  </div>
                </el-image>
              </div>
            </div>
            <div class=" img-box justify-content" v-else>无</div>
          </template>
        </el-table-column>
        <el-table-column property="remark" label="备注" align="center"/>
        <el-table-column property="createBy" label="操作人" align="center"/>
        <el-table-column property="createTime" label="操作时间" align="center"/>
        <el-table-column label="操作" align="center"
                         v-if="(($auth.hasPermi('after:workorder:service:edit') || $auth.hasPermi('after:workorder:service:remove')) && workorder.status === '进行中') || $auth.hasPermi('after:workorder:edit')">
          <template slot-scope="scope">
            <el-button type="text" icon="el-icon-edit"
                       v-if="$auth.hasPermi('after:workorder:service:edit') || $auth.hasPermi('after:workorder:edit')"
                       @click="openDialog(scope.row)">修改
            </el-button>
            <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                           @confirm="deleteHandler(scope.row)">
              <el-button slot="reference" icon="el-icon-delete"
                         v-if="$auth.hasPermi('after:workorder:service:remove') || $auth.hasPermi('after:workorder:edit')"
                         type="text" style="margin-left: 10px">删除
              </el-button>
            </el-popconfirm>
          </template>
        </el-table-column>
      </el-table>

      <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
                  @pagination="getList"/>
    </div>

    <div v-else class="infinite-box" style="max-height: 500px;overflow: auto;">
      <ul class="infinite-list" v-infinite-scroll="handleLoad">
        <li v-for="item in tableData" :key="item.id" class="infinite-list-item">
          <el-card class="box-card">
            <div slot="header" class="clearfix">
              <span>{{ item.createTime }}</span>
              <div style="float: right;">
                <el-button type="text"
                           v-if="$auth.hasPermi('after:workorder:work:edit') || $auth.hasPermi('after:workorder:edit')"
                           @click="openDialog(item)" style="padding: 3px 0;">修改
                </el-button>
                <el-popconfirm confirm-button-text="是" cancel-button-text="否" title="确定删除吗？"
                               @confirm="deleteHandler(item)">
                  <el-button slot="reference"
                             v-if="$auth.hasPermi('after:workorder:work:remove') || $auth.hasPermi('after:workorder:edit')"
                             type="text" style="margin-left: 10px;padding: 3px 0;">删除
                  </el-button>
                </el-popconfirm>
              </div>
            </div>
            <div class=" cus_text">
              <div class="flex">
                <span>设备名称: </span>
                <span class="flex-1">{{ item.name }}</span>
              </div>
              <div class="flex">
                <span>数量: </span>
                <span class="flex-1">{{ item.num }}</span>
              </div>
              <div class="flex">
                <span>状态: </span>
                <span class="flex-1">{{ item.status }}</span>
              </div>
              <div class="flex">
                <span>现状态: </span>
                <span class="flex-1">{{ item.nowStatus }}</span>
              </div>
              <div class="flex" v-if="item.description">
                <span>维修简述: </span>
                <span class="flex-1">{{ item.description }}</span>
              </div>
              <div class="flex">
                <span>操作人: </span>
                <span class="flex-1">{{ item.createBy }}</span>
              </div>
              <div class="flex" v-if="item.remark">
                <span>备注: </span>
                <span class="flex-1">{{ item.remark }}</span>
              </div>
              <div class="flex" v-if="item.deviceImage.length > 2">
                <span>设备图片: </span>
                <div class="flex-1">
                  <el-image
                    style="width: 50px; height: auto;"
                    fit="contain"
                    :src="env + item.deviceImage.split(',')[0]"
                    :preview-src-list="item.deviceImage.split(',').map(i=> (env + i))"
                  >
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
              </div>
              <div class="flex" v-if="item.maintainImage.length > 2">
                <span>维修图片: </span>
                <div class="flex-1">
                  <el-image
                    style="width: 50px; height: auto;"
                    fit="contain"
                    :src="env + item.maintainImage.split(',')[0]"
                    :preview-src-list="item.maintainImage.split(',').map(i=> (env + i))"
                  >
                    <div slot="error" class="image-slot">
                      <i class="el-icon-picture-outline"></i>
                    </div>
                  </el-image>
                </div>
              </div>
            </div>
          </el-card>
        </li>
      </ul>

      <div v-if="loading" style="text-align: center;color: #909399;"><i class="el-icon-loading"></i> 正在加载</div>
      <div v-else-if="tableData.length <= 0" style="text-align: center;color: #909399;">暂无数据</div>
      <div v-else-if="!queryParams.hasNextPage" style="text-align: center;color: #909399;">暂无更多数据</div>

      <el-backtop target=".infinite-box"></el-backtop>
    </div>

    <el-dialog :title="dialogTitle === 1 ? '新增' : '修改'" :visible.sync="dialogVisible" width="700px"
               :close-on-click-modal="false" :fullscreen="device == 'mobile'">
      <el-form :model="form" :rules="rules" ref="formRef" class="demo-form"
               :label-position="'top'">
        <el-form-item label="设备名称" prop="name">
          <el-select v-model="form.name" placeholder="请选择设备名称" style="width: 100%;">
            <el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.name">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="设备数量" prop="num">
          <el-input-number v-model.trim="form.num" placeholder="请输入设备数量"/>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="form.status" placeholder="请选择状态" style="width: 100%;">
            <el-option v-for="item in statusList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="现状态" prop="nowStatus">
          <el-select v-model="form.nowStatus" placeholder="请选择现状态" style="width: 100%;">
            <el-option v-for="item in nowStatusList" :key="item.value" :label="item.label" :value="item.value">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="维修简述" prop="description">
          <el-input v-model.trim="form.description" type="textarea" :maxlength="500" placeholder="请输入维修简述"
                    :autosize="{ minRows: 2 }"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model.trim="form.remark" type="textarea" :maxlength="250" placeholder="请输入备注"
                    :autosize="{ minRows: 2 }"/>
        </el-form-item>
        <el-form-item label="设备图片" prop="deviceImage">
          <el-upload class="upload-demo" ref="upload" action="#" :limit="9" :on-change="handleChange"
                     :on-remove="handleRemove" :file-list="fileList" :auto-upload="false" accept=".jpg,.jpeg,.png,.gif"
                     list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="维修图片" prop="maintainImage">
          <el-upload class="upload-demo" ref="upload2" action="#" :limit="9" :on-change="handleChange2"
                     :on-remove="handleRemove2" :file-list="fileList2" :auto-upload="false"
                     accept=".jpg,.jpeg,.png,.gif" list-type="picture"
          >
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件</div>
          </el-upload>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" :loading="uploadLoading" @click="submitForm('formRef')">提交</el-button>
        <el-button @click="dialogVisible = false">取消</el-button>
      </div>
    </el-dialog>

    <el-dialog :visible.sync="imgDialogVisible" width="800px" :fullscreen="device == 'mobile'">
      <img width="100%" height="auto" style="object-fit: contain;" :src="imgDialogUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import {
  addDataApi,
  deleteDataApi,
  getDataListApi,
  updateDataApi,
  uploadImgApi
} from "@/api/after/workorder/deviceService";
import {getUserProfile} from "@/api/system/user";
import {getDataListApi as getAllProductApi} from "@/api/crm/md/school/product";
import {throttle} from "@/utils";
import {mapGetters} from 'vuex'

export default {
  name: 'DeviceService',
  // dicts: ['sys_project_schedule'],
  data() {
    return {
      uploadLoading: false, // 按钮加载
      imgDialogUrl: "",// 预览图链接
      env: process.env.VUE_APP_STATIC_API || '',
      imgDialogVisible: false, // 预览图片的弹框
      // 记录上一次打开弹窗是修改or增加
      // null 增加
      // 非null 修改
      formId: null,
      // 加载动画
      loading: true,
      // 弹框标题 1是增加 其他是修改
      dialogTitle: 1,
      // 弹框显示
      dialogVisible: false,
      // 新增和修改参数
      form: {
        name: "", // 设备名称
        num: 1, // 设备数量
        workorderId: 0,
        createBy: "", // 创建人
        createTime: "", // 创建时间
        id: null,
        remark: "", // 备注
        updateBy: "",
        updateTime: "",
        status: "", // 设备状态（可选值：偶尔使用、经常使用、开课教学、培训比赛、需维修、闲置）
        nowStatus: "", // 设备当前状态（可选值：正常使用、培训后使用、维修恢复、未恢复）
        description: "", // 维修简述
        deviceImage: "", // 设备照片路径
        maintainImage: "", // 维修照片路径
      },
      statusList: [
        {
          value: "偶尔使用",
          label: "偶尔使用"
        },
        {
          value: "经常使用",
          label: "经常使用"
        },
        {
          value: "开课教学",
          label: "开课教学"
        },
        {
          value: "培训比赛",
          label: "培训比赛"
        },
        {
          value: "需维修",
          label: "需维修"
        },
        {
          value: "闲置",
          label: "闲置"
        },
        {
          value: "其他",
          label: "其他"
        },
      ],
      nowStatusList: [
        {
          value: "正常使用",
          label: "正常使用"
        },
        {
          value: "培训后使用",
          label: "培训后使用"
        },
        {
          value: "维修恢复",
          label: "维修恢复"
        },
        {
          value: "未恢复",
          label: "未恢复"
        },
        {
          value: "其他",
          label: "其他"
        },
      ],
      // 表单的校验规则
      rules: {
        name: [
          {required: true, message: '请选择设备', trigger: 'change'}
        ],
        status: [
          {required: true, message: '请选择状态', trigger: 'change'}
        ],
        nowStatus: [
          {required: true, message: '请选择现状态', trigger: 'change'}
        ],
        // deviceImage: [
        //   { required: true, message: '请上传设备图片', trigger: 'change' }
        // ],
        num: [
          {required: true, message: '请输入设备数量', trigger: 'blur'}
        ],
      },
      // 表格数据
      tableData: [],
      // 总数条数
      total: 0,
      // 查询参数
      queryParams: {
        workorderId: null,
        createBy: "", // 学校名 *
        province: "", // 省份 *
        startDate: "",
        endDate: "",
        pageNum: 1,
        pageSize: 10,
        pages: 0, // 总页数
        hasNextPage: false, // 还有下一页
      },
      // 用户信息
      user: {},
      roleGroup: {},
      postGroup: {},
      // 图片列表
      fileList: [],
      fileList2: [],
      // 产品列表
      productList: [],
    }
  },
  props: {
    workorder: {
      type: Object,
      required: true
    }
  },
  computed: {
    ...mapGetters([
      'device'
    ])
  },
  watch: {
    workorder: {
      handler(newV) {
        this.form.workorderId = newV.id
        this.queryParams.workorderId = newV.id

        if (newV.id) {
          this.getList()
          this.getAllProduct()
        }
      },
      deep: true,
      immediate: true
    }
  },
  created() {
    this.getUserinfo()
  },
  methods: {
    // 下拉加载
    handleLoad: throttle(function() {
      if(!this.queryParams.hasNextPage) {
        return false
      }
      this.queryParams.pageNum += 1
      this.getList({ isConnect: true })
    }, 2000),
    // 查看图片
    handlePictureCardPreview(url) {
      this.imgDialogUrl = this.env + url
      this.imgDialogVisible = true;
    },
    // 上传全部图片
    async uploadImg(fileList = [], cb = () => {
    }) {
      const urlList = (fileList ?? []).filter(i => !i.raw).map(i => i.url.replace(this.env, ""))
      const list = (fileList ?? []).filter(i => i.raw).map((item) => {
        const formData = new FormData()
        formData.append('file', item.raw)
        return uploadImgApi(formData)
      })

      try {
        const imgList = (await Promise.all(list) ?? []).map(item => item?.fileName ?? "") ?? []
        const fileListStr = [...urlList, ...imgList].join(',')
        cb && cb(fileListStr)
      } catch (e) {
      }
    },
    // 删除图片
    handleRemove(_, fileList) {
      this.fileList = fileList
    },
    // 删除图片
    handleRemove2(_, fileList) {
      this.fileList2 = fileList
    },
    // 选中图片
    handleChange(_, fileList) {
      this.fileList = fileList
    },
    // 选中图片
    handleChange2(_, fileList) {
      this.fileList2 = fileList
    },
    // 获取用户信息
    getUserinfo() {
      getUserProfile().then(response => {
        this.user = response.data;
        this.roleGroup = response.roleGroup;
        this.postGroup = response.postGroup;
      });
    },
    // 获取数据
    async getList(options) {
      this.loading = true
      const res = await getDataListApi(this.queryParams)
      if (res.code === 200) {
        if(options?.isConnect) {
          const list = res.data.list ?? []
          this.tableData = [...this.tableData, ...list]
        } else {
          this.tableData = res.data.list ?? []
        }

        this.total = res.data.total ?? 0
        this.queryParams.pages = res.data.pages ?? 0
        this.queryParams.hasNextPage = res.data.hasNextPage
      }
      this.loading = false
    },
    // 搜索的回调
    searchHandler() {
      this.queryParams.pageNum = 1
      this.getList()
    },
    // 删除的回调
    async deleteHandler(row) {
      const res = await deleteDataApi({
        id: row.id
      })
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 获取全部产品
    async getAllProduct() {
      const params = {
        facultyId: this.workorder.facultyId,
        agentId: this.workorder.agentId,
      }

      const res = await getAllProductApi(params)
      if (res.code === 200) {
        this.productList = res.data?.list?.rows ?? []
      }
    },
    // 打开弹窗
    openDialog(row) {
      if (row) {
        this.formId = row.id
        this.form = {...row}
        this.fileList = ((row.deviceImage ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: this.env + item
        }))
        this.fileList2 = ((row.maintainImage ?? "").split(',') ?? []).filter(i => i).map(item => ({
          name: item,
          url: this.env + item
        }))
        this.dialogTitle = 2
      } else {
        if (this.formId) {
          this.form = {...this.$options.data().form}
          this.fileList = []
          this.fileList2 = []
        }
        this.formId = null
        this.dialogTitle = 1
      }
      this.dialogVisible = true
      // this.resetForm('formRef')
      this.$nextTick(() => {
        this.$refs['formRef'].clearValidate();
        // this.resetForm('formRef')
      })
    },
    // 导出的回调
    async exportHandler() {
      this.download('crm/newspaper/export', {
        ...this.queryParams,
        userId: this.user.userId,
        deptId: this.user.deptId,
      }, `newspaper_${new Date().getTime()}.xlsx`)
    },
    // 表单提交
    submitForm(formName) {
      if (this.form.isImportant === 1 && !(this.form.basis)) {
        this.$notify({
          title: '警告',
          message: '请选择重点依据',
          type: 'warning'
        });
        return false
      }
      const _this = this
      this.$refs[formName].validate(async (valid) => {
        if (valid) {
          try {
            this.uploadLoading = true
            await this.uploadImg(this.fileList, (fileListStr) => {
              _this.form.deviceImage = fileListStr
            })

            await this.uploadImg(this.fileList2, (fileListStr) => {
              _this.form.maintainImage = fileListStr
            })
          } catch (error) {
            this.uploadLoading = false
          }

          this.uploadLoading = false

          if (!this.form.workorderId) {
            this.form.workorderId = +this.$route.query.workorderId
          }

          if (this.dialogTitle === 1) {
            this.addDataHandler()
          } else {
            this.updateDataHandler()
          }
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 增加数据的回调
    async addDataHandler() {
      const payload = {
        ...this.form,
        deptId: this.user.deptId,
        userId: this.user.userId,
        createBy: this.user.nickName,
        updateBy: this.user.nickName,
      }
      const res = await addDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.fileList = []
        this.fileList2 = []
        this.dialogVisible = false
        this.$refs['formRef'].resetFields();
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 修改数据的回调
    async updateDataHandler() {
      const payload = {
        ...this.form,
        updateBy: this.user.nickName,
      }
      const res = await updateDataApi(payload)
      if (res.code === 200) {
        this.$message({
          message: res.msg,
          type: 'success'
        });
        this.getList()
        this.dialogVisible = false
      } else {
        this.$message({
          message: res.msg,
          type: 'error'
        });
      }
    },
    // 重置表单
    resetForm(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].resetFields();
      }
    },
    // 重置的回调
    resetHandler() {
      this.resetForm('queryFormRef')
    },
  },
}
</script>

<style scoped lang="scss">

.flex {
  display: flex;
}

.justify-content {
  justify-content: center;
}

.infinite-list {
  padding: 0;

  .infinite-list-item {
    margin: 8px 0;
    list-style: none;
  }

  .cus_text {
    & > div {
      margin: 10px auto;

      & > span:first-child {
        display: inline-block;
        width: 80px;
        font-weight: bolder;
        text-align: right;
        margin-right: 8px;
      }
    }
  }

  .flex {
    display: flex;
  }

  .items-center {
    align-items: center;
  }

  .flex-1 {
    flex: 1;
  }
}
</style>
